﻿package com.thorqq.magictimer.download;

import com.thorqq.magictimer.timeLoop.TimerMgr;
import com.thorqq.magictimer.util.Util;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.SparseArray;

public class DownloadProxy
{
    private boolean binded = false;
    private DownloadSvc.MyBinder mBinder;

    static private DownloadSvcConnListener mListenerConn;
    static private DownloadSvcUpdateListener mListenerUpdate;
    static private Context mContext;
    static private DownloadProxy mInstance;

    static private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            if (mListenerUpdate != null && msg.what == DownloadSvc.MSG_DOWNLOAD_INFO)
            {
                mListenerUpdate.onDownloadInfoUpdate();
            }

        }
    };
    
    static public void init(Context c)
    {
        mContext = c;
    }

    static public DownloadProxy getInstance()
    {
        if (mInstance == null)
        {
            mInstance = new DownloadProxy(mContext);
        }
        return mInstance;
    }

    private DownloadProxy(Context c)
    {
        mContext = c;
    }

    public void registerConnListener(DownloadSvcConnListener l)
    {
        mListenerConn = l;
    }

    public void registerUpdateListener(DownloadSvcUpdateListener l)
    {
        mListenerUpdate = l;
    }

    public void startDownloadSvc()
    {
        // 启动并绑定service
        Intent intent = new Intent(mContext, DownloadSvc.class);
        mContext.startService(intent);
        mContext.bindService(intent, mConn, Context.BIND_AUTO_CREATE);
    }

    public void stopDownloadSvc()
    {
        int isDownloading = -1;
        if (mBinder != null)
        {
            if(mBinder.isDownloading())
            {
                isDownloading = 1;
            }
            else
            {
                isDownloading = 0;
            }
        }

        // 先解绑。由于之前是通过startService方式启动服务，所以这里的unbind不会终止服务
        unbind();

        // 如果没有正在下载的任务，则停止服务
        if (isDownloading == 0)
        {
            Intent intent = new Intent(mContext, DownloadSvc.class);
            Util.log("DownloadProxy.stopService()");
            mContext.stopService(intent);
        }
    }

    public SparseArray<TaskInfo> getAllTask()
    {
        return mBinder.getAllTask();
    }

    // 新建下载
    public TaskInfo initDownloader(String url, String path)
    {
        if (mBinder != null)
        {
            return mBinder.initDownloader(url, path);
        } 
        else
        {
            return null;
        }
    }

    public void initDownloaderDirectly(String url, String path, boolean autoInstall)
    {        
        if (mBinder != null)
        {
            mBinder.initDownloaderAndInstall(url, path, autoInstall);
        } 
        else
        {
            Intent intent = new Intent(mContext, DownloadSvc.class);

            intent.putExtra(TimerMgr.ALARM_INTENT_DOWNLOAD_URL, url);
            intent.putExtra(TimerMgr.ALARM_INTENT_DOWNLOAD_FILENAME, path);
            intent.putExtra(TimerMgr.ALARM_INTENT_DOWNLOAD_AUTO_INSTALL, 
                    autoInstall == true ? DownloadSvc.AUTO_INSTALL : DownloadSvc.AUTO_INSTALL_NO);
            mContext.startService(intent);
//            mContext.bindService(intent, mConn, Context.BIND_AUTO_CREATE);
        }
    }
    
    public TaskInfo initDownloader(int taskid)
    {
        return mBinder.initDownloader(taskid);
    }

    // 判断某个任务是否正在下载
    public boolean isDownloading(int taskid)
    {
        return mBinder.isDownloading(taskid);
    }

    public boolean isDownloading()
    {
        return mBinder.isDownloading();
    }

    // 启动或者停止一个任务
    public void startOrStop(int taskid)
    {
        mBinder.startOrStop(taskid);
    }
    
    //重新开始下载
    public void restart(int taskid)
    {
        mBinder.restart(taskid);
    }

    // 删除一个任务。如果正在下载，则要先停止，然后再删除
    public void delete(int taskid)
    {
        mBinder.delete(taskid);
    }
    
    public boolean isToPause(int taskid)
    {
        return mBinder.isToPause(taskid);
    }
    
    public boolean isToStart(int taskid)
    {
        return mBinder.isToStart(taskid);
    }


    /**
     * 解除绑定
     * 
     * @param view
     */
    private void unbind()
    {
        Util.log("DownloadProxy.unbind(): binded = " + binded);
        if (binded)
        {
            mBinder.registerHandler(null);
            mContext.unbindService(mConn);
            mBinder = null;
            binded = false;
        }
    }

    private ServiceConnection mConn = new ServiceConnection()
    {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            Util.log("onServiceConnected called.");
            mBinder = (DownloadSvc.MyBinder) service;
            mBinder.registerHandler(mHandler);
            binded = true;

            if (mListenerConn != null)
            {
                mListenerConn.onServiceConnected();
            }

        }

        // 在服务崩溃或被杀死导致的连接中断时被调用，而如果我们自己解除绑定时则不会被调用
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            Util.log("onServiceDisconnected called.");
            mBinder.registerHandler(null);
            binded = false;
            mBinder = null;
        }
    };

}